import * as mongoose from 'mongoose';

import fastFormatTimeSchema from './base';
import paginate from './plugins/paginate';
import autoPopulateSubs from './plugins/auto-populate-subs';

const { Schema } = mongoose;

const subscribeSchema = new Schema(
  {
    product: {
      type: Schema.Types.Number,
      enum: [0, 1],
    },
    blog: {
      type: Schema.Types.Number,
      enum: [0, 1],
    },
    email: Schema.Types.String,
    locale: {
      type: Schema.Types.ObjectId,
      ref: 'dictionary',
    },
    ...fastFormatTimeSchema(),
  },
  {
    versionKey: false,
    timestamps: true,
    toJSON: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        ret.blog = Boolean(ret.blog);
        ret.product = Boolean(ret.product);
        delete ret._id;
      },
    },
    toObject: {
      getters: true,
      transform(doc, ret) {
        ret.id = ret._id;
        ret.blog = Boolean(ret.blog);
        ret.product = Boolean(ret.product);
        delete ret._id;
      },
    },
  },
);

export default paginate(
  autoPopulateSubs({
    schema: subscribeSchema,
    methods: ['find', 'findOne'],
    path: 'locale',
    select: 'id name value',
  }),
);
